$(function () {
  var layer = layui.layer;
  var form = layui.form;
  articlePoints();
  // 获取文章分类的列表
  function articlePoints() {
    $.ajax({
      type: "GET",
      url: "/my/article/cates",
      success: function (res) {
        var htmlStr = template("tpl", res);
        $("tbody").html(htmlStr);
      },
    });
  }
  // 为添加类别添加点击事件
  var index = null;
  $("#add").on("click", function () {
    index = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "添加文章类别",
      content: $("#open-add").html(),
    });
  });
  // 监听表单提交事件
  $("body").on("submit", "#form-add", function (e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: "/my/article/addcates",
      data: $(this).serialize(),
      success: function (res) {
        if (res.status !== 0) return layer.msg(res.message);
        articlePoints();
        layer.msg(res.message);
        // 根据索引 关闭弹出层
        layer.close(index);
      },
    });
  });
  //编辑按钮的点击事件
  var indexEdit = null;
  $("tbody").on("click", "#edit", function () {
    indexEdit = layer.open({
      type: 1,
      area: ["500px", "250px"],
      title: "修改文章类别",
      content: $("#open-edit").html(),
    });
    // 获取当前文章类别的信息
    var id = $(this).attr("data-id");
    // 发起请求获取对应的数据
    $.ajax({
      type: "GET",
      url: "/my/article/cates/" + id,
      success: function (res) {
        console.log(res.data);
        form.val("form1-edit", res.data);
      },
    });
  });
  // 为修改分类表单修改submit事件
  $("body").on("submit", "#form-edit", function (e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: "/my/article/updatecate",
      data: $(this).serialize(),
      success: function (res) {
        if (res.status !== 0) return layer.msg(res.message);
        layer.msg(res.message);
        layer.close(indexEdit);
        articlePoints();
      },
    });
  });
  // 删除类别
  $("tbody").on("click", ".btn-delete", function () {
    var id = $(this).attr("data-id");
    // 提示用户是否要删除
    layer.confirm("确认删除", { icon: 3, title: "提示" }, function (index) {
      $.ajax({
        type: "GET",
        url: "/my/article/deletecate/" + id,

        success: function (res) {
          if (res.status !== 0) return layer.msg(res.message);
          layer.msg(res.message);
          // 关闭弹窗
          layer.close(index);
          // 重新获取文章列表
          articlePoints();
        },
      });
    });
  });
});
